package 多线程练习;

//import 多线程练习.Restaurant.Order;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class order{
    private final int id;
    private final String customerName;
    public order(int id, String customerName) {
        this.id = id;
        this.customerName = customerName;
    }
    @Override
    public String toString(){
        return "Order{id"+id +",customer= '"+customerName+"'}";
    }
}
class OrderQueue{
    private final Queue<order> queue=new LinkedList<>();
    private final int maxSize;
    private final ReentrantLock lock=new ReentrantLock();
    private final Condition notEmpty = lock.newCondition();
    private final Condition notFull = lock.newCondition();
    //设置订单最大值
    public OrderQueue(int maxSize){
        this.maxSize=maxSize;
    }
    //加入订单，服务员用
    public void addOrder(order order) throws InterruptedException{
        lock.lock();
        try{
            while(queue.size()==maxSize){
                System.out.println("队列已满，服务员等待");
                notFull.await();
            }
            queue.offer(order);
            System.out.println("新订单加入队列"+order+" , "+Thread.currentThread().getName());
            notEmpty.signalAll();
        }finally{
            lock.unlock();
        }
    }

    //消费订单，厨师用
    public order takeOrder() throws InterruptedException {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                System.out.println("队列为空，厨师等待...");
                notEmpty.await();
            }
            order order = queue.poll();
            notFull.signalAll(); // 通知服务员
            return order;
        } finally {
            lock.unlock();
        }
    }
    public boolean isEmpty(){
        lock.lock();
        try{
            return queue.isEmpty();
        }finally{
            lock.unlock();
        }
    }
}
class OrderIdGenerator {
    // 静态原子计数器，保证全局唯一
    private static final AtomicInteger idCounter = new AtomicInteger(1);

    public static int getNextId() {
        return idCounter.getAndIncrement();
    }
}

class waiter implements Runnable{
    private final OrderQueue orderQueue;
    private volatile boolean isRunning=true;
//    private static AtomicInteger orderId=new AtomicInteger(1);
    public waiter(OrderQueue orderQueue){
        this.orderQueue=orderQueue;
    }
    public void stop(){
        isRunning=false;
    }
    @Override
    public void run() {
        try {
            while (isRunning) {
                // 使用全局唯一ID
                int currentId = OrderIdGenerator.getNextId();
                String customer = "顾客-" + (currentId + 1);
                order order = new order(currentId, customer);
                orderQueue.addOrder(order);
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

}
class chef implements Runnable{
    private final OrderQueue orderQueue;
    private volatile boolean isRunning=true;
    public chef(OrderQueue orderQueue){
        this.orderQueue=orderQueue;
    }
    public void stop(){
        isRunning=false;
    }
    @Override
    public void run(){
        System.out.println("Chef启动: " + Thread.currentThread().getName());
        try{
            while(isRunning || !orderQueue.isEmpty()){
                order order=orderQueue.takeOrder();
                System.out.println("初始开始烹饪"+order);
                Thread.sleep(2000);
                System.out.println("烹饪完成...");
            }
        }catch(InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        System.out.println("厨师下班了！");
    }
}
public class RestaurantSimulation {
    public static void main(String[] args) throws InterruptedException {
        OrderQueue orderQueue=new OrderQueue(5);
//        ExecutorService executor=Executors.newFixedThreadPool(5);
        waiter waiter1=new waiter(orderQueue);
        waiter waiter2=new waiter(orderQueue);
        chef chef1=new chef(orderQueue);
        chef chef2=new chef(orderQueue);
        chef chef3=new chef(orderQueue);
        ExecutorService executor=Executors.newFixedThreadPool(5);
        executor.execute(waiter1);
        executor.execute(waiter2);
        executor.execute(chef1);
        executor.execute(chef2);
        executor.execute(chef3);
//        new Thread(waiter1,"waiter1").start();
//        new Thread(waiter2,"waiter2").start();
//        new Thread(chef1,"chef1").start();
//        new Thread(chef2,"chef2").start();
//        new Thread(chef3,"chef3").start();
        Thread.sleep(10000);
        waiter1.stop();
        waiter2.stop();
        chef1.stop();
        chef2.stop();
        chef3.stop();
//        executor.shutdown();
//        if(!executor.awaitTermination(5, TimeUnit.SECONDS)){
//            System.out.println("强制关闭剩余任务");
//            executor.shutdownNow();
//        }
        System.out.println("餐厅打烊！");
    }

}
